
from django import forms
from django.http import HttpResponseRedirect
from native_tags.decorators import block
from genericview.views import HttpRedirectException, namespace_get
from pirate_permissions.models import PermissionsGroup

get_namespace = namespace_get("pp_permissions")

@block
def pp_permgroup_list(context, nodelist, *args, **kwargs):

    context.push()
    namespace = get_namespace(context)

    active = kwargs.pop('active', None)
    if active is not None:
        active = True if active == "True" else False
        namespace["groups"] = PermissionsGroup.objects.filter(is_active=active).all()
    else:
        namespace["groups"] = PermissionsGroup.objects.all()

    output = nodelist.render(context)
    context.pop()

    return output


@block 
def pp_permgroup_form(context, nodelist, *args, **kwargs):

    context.push()
    namespace = get_namespace(context)

    POST = kwargs.pop('POST', None)
    path = kwargs.pop('path', "/")
    if POST and POST.get("form_id") == "perm-group-form":
        form = GroupForm(POST)
        if form.is_valid():
            new_group = form.save()
            raise HttpRedirectException(HttpResponseRedirect(path))
    else:
        form = GroupForm()

    namespace['form'] = form
    output = nodelist.render(context)
    context.pop()

    return output


class GroupForm(forms.ModelForm):
    class Meta:
        model = PermissionsGroup 

    form_id = forms.CharField(widget=forms.HiddenInput(), initial="perm-group-form")

